# _*_ code:utf-8 _*_

import pymysql
from ..settings import MYSQL_CONNECT


class MysqlHelper:

    def __init__(self):
        self.host = MYSQL_CONNECT['MYSQL_HOST']
        self.port = MYSQL_CONNECT['MYSQL_PORT']
        self.db = MYSQL_CONNECT['MYSQL_DB']
        self.user = MYSQL_CONNECT['MYSQL_USER']
        self.password = MYSQL_CONNECT['MYSQL_PASSWD']
        self.charset = MYSQL_CONNECT['MYSQL_CHARSET']
        self.conn = pymysql.connect(host=self.host, port=self.port, db=self.db, user=self.user, passwd=self.password,
                                    charset=self.charset)
        # 创建游标
        self.cursor = self.conn.cursor()

    def close(self):
        self.cursor.close()
        self.conn.close()

    # 增加
    def insert(self, sql, params=()):
        return self._edit(sql, params)

    # 删除
    def delete(self, sql, params=()):
        return self._edit(sql, params)

    # 修改
    def update(self, sql, params=()):
        return self._edit(sql, params)

    # 增删改其实都是调用编辑
    def _edit(self, sql, params):
        count = 0
        try:
            # 开启连接
            self.connect()
            # 执行游标
            count = self.cursor.execute(sql, params)
            # 提交事物
            self.conn.commit()
            # 关闭连接
            self.close()
        # 捕捉异常
        except Exception as e:
            # 抛出异常并打印
            raise e
            print(e)
        # 返回结果
        return count

